<?php
declare(strict_types=1);

namespace Modules\School\Http\Controllers;

use Catch\Base\CatchController as Controller;
use http\Message\Body;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\School\Models\School;
use Illuminate\Http\Request;
use Modules\User\Models\K12User;


class SchoolController extends Controller
{
    public function __construct(
        protected readonly School $model
    ){}

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        return $this->model->getList();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try{
            $school_id = $this->model->storeBy($request->all());
            $k12_users_info = K12User::find($request->k12_users);
            $school_ids = $k12_users_info->school_id;
            $school_ids[] = $school_id;
            $k12_users_info->school_id = $school_ids;
            $k12_users_info->save();
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage(), $e->getTrace());
            return false;
        }
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return $this->model->deleteBy($id);
    }

    /**
     * enable
     *
     * @param $id
     * @return bool
     */
    public function enable($id)
    {
        return $this->model->toggleBy($id);
    }
}
